import { IHttpResponse, IParam } from '@/core/interface';
import { ControlVOBase } from '../control-vo';
import { CtrlServiceBase } from './ctrl-service-base';

class MultiEditViewPanelService<
	T extends ControlVOBase
> extends CtrlServiceBase<T> {
	/**
	 * 处理响应
	 *
	 * @param {IHttpResponse} response
	 * @param {*} [opts={}]
	 * @return {*}
	 * @memberof MultiEditViewPanelService
	 */
	handleResponse(response: IHttpResponse, opts: any = {}) {
		let result = null;
		if (response.data instanceof Array) {
			result = [];
			response.data.forEach((item: any, index: number) => {
				result.push(this.newControlVO(item));
			});
		} else {
			result = this.newControlVO(response.data);
		}
		response.data = result;
		return response;
	}

	/**
	 * 查询数据
	 *
	 * @param {string} action
	 * @param {IParam} [context={}]
	 * @param {IParam} [data={}]
	 * @return {*}  {Promise<IHttpResponse>}
	 * @memberof MultiEditViewPanelService
	 */
	async get(
		action: string,
		context: IParam = {},
		data: IParam = {}
	): Promise<IHttpResponse> {
		const { data: Data, context: Context } = this.handleRequestData(
			context,
			data
		);
		try {
			await this.beforeAsyncAction();
			const response = await this.appEntityService[action ? action : 'Get'](
				Context,
				Data
			);
			this.handleResponse(response);
			return response;
		} catch (error) {
			return { data: error, success: false };
		}
	}

	/**
	 * 删除
	 *
	 * @param {string} action
	 * @param {IParam} [context={}]
	 * @param {IParam} [data={}]
	 * @return {*}  {Promise<IHttpResponse>}
	 * @memberof MultiEditViewPanelService
	 */
	async delete(
		action: string,
		context: IParam = {},
		data: IParam = {}
	): Promise<IHttpResponse> {
		const { data: Data, context: Context } = this.handleRequestData(
			context,
			data
		);
		try {
			await this.beforeAsyncAction();
			const response = await this.appEntityService[action ? action : 'Remove'](
				Context,
				Data
			);
			this.handleResponse(response);
			return response;
		} catch (error) {
			return { data: error, success: false };
		}
	}

	/**
	 * 加载草稿
	 *
	 * @param {string} action
	 * @param {IParam} [context={}]
	 * @param {IParam} [data={}]
	 * @return {*}  {Promise<IHttpResponse>}
	 * @memberof MultiEditViewPanelService
	 */
	async loadDraft(
		action: string,
		context: IParam = {},
		data: IParam = {}
	): Promise<IHttpResponse> {
		const { data: Data, context: Context } = this.handleRequestData(
			context,
			data
		);
		try {
			await this.beforeAsyncAction();
			const response = await this.appEntityService[
				action ? action : 'GetDraft'
			](Context, Data);
			this.handleResponse(response);
			return response;
		} catch (error) {
			return { data: error, success: false };
		}
	}
}
export default MultiEditViewPanelService;
